<?php
namespace Common\Models;
use Common\BaseModel;
class TGoldBeanTask extends BaseModel
{
    public $res;
    public $expire;
    public function initialize()
    {
        parent::initialize();
        $this->setSource('t_gold_bean_task');
    }


    /**
     * 获取金豆任务列表
     */
    public function goldTaskList($user_id)
    {
        $todayDatetime = timeChange(1);
        $where = [
            ["show", "=", 1],
            ["task_num",">",0]
        ];
        $getList = $this->tgoldBeanTask::query()
            ->select(["task_id", "icon", "name", "describe", "gold_bean", "task_num", "event_id"])
            ->where($where)
            ->orderBy("sort", 'asc')
            ->get()
            ->toArray();
        foreach ($getList as $key => $value) {

            $eventNo = '';
            $eventParams = '';
            if ($value['event_id'] > 0) {
                $eventInfo = $this->routeEventModel::find($value['event_id']);
                if ($eventInfo && $eventInfo->status == 1 && $eventInfo->deleted == 0) {
                    $eventNo = $eventInfo->event_no;
                    $eventParams = $eventInfo->event_params;
                }
            }
            $getList[$key]['eventNo'] = $eventNo;
            $getList[$key]['eventParams'] = $eventParams;

            $walletsGoldBean = $this->walletsGoldBeanLog($user_id, $value['task_id'], $todayDatetime);
            $getList[$key]['finishCount'] = $walletsGoldBean['count'];
            $getList[$key]['todayGain'] = (int)$walletsGoldBean['sum'];
        }
        return $getList;
    }


    /**
     * 查看今天的任务次数是否已经完成
     */
    public function walletsGoldBeanLog($user_id, $type, $datetime = [])
    {
        $where = [
            ['user_id', '=', $user_id],
            ['type', '=', $type],
            ['created', ">=", $datetime['start_at']],
            ['created', "<=", $datetime['end_at']]
        ];
        $goldBeanSum = $this->taUserWalletsGoldBeanLog::query()
            ->selectRaw("count(user_id) as count,sum(num) as sum")
            ->where($where)
            ->first();
        if ($goldBeanSum) {
            $responseResult = $goldBeanSum->toArray();
        } else {
            $responseResult = [
                'count' => 0,
                'sum' => 0
            ];
        }
        $responseResult['sum'] = (isset($responseResult['sum']) && !empty($responseResult['sum'])) ? (int)$responseResult['sum'] : 0;
        return $responseResult;
    }



}
